package com.mxx.common.data.utils;

import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: mxx
 * @date: 2021/11/5
 * @time: 14:39
 * @Description: 描述信息
 */
public class JpaClassUtil {
    public static Field[] getFieldListOfJpaOperator(Class classes) {
        List<Field> fieldList = new ArrayList<>();
        eachFieldOnJpa(fieldList, classes);
        return fieldList.toArray(new Field[fieldList.size()]);
    }

    public static Field[] getFieldListOfNoJpaOperator(Class classes) {
        List<Field> fieldList = new ArrayList<>();
        eachFieldNoJpa(fieldList, classes);
        return fieldList.toArray(new Field[fieldList.size()]);
    }


    private static void eachFieldOnJpa(List<Field> fieldList, Class classes) {
        for (Field field : classes.getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers) || !Modifier.isPrivate(modifiers)) {
                continue;
            }
            Transient aTransient = field.getAnnotation(Transient.class);
            if (aTransient == null) {
                field.setAccessible(true);
                fieldList.add(field);
            }
        }
        Class superClass = classes.getSuperclass();
        if (superClass != null && superClass.getAnnotation(MappedSuperclass.class) != null) {
            eachFieldOnJpa(fieldList, superClass);
        }

    }

    private static void eachFieldNoJpa(List<Field> fieldList, Class classes) {
        for (Field field : classes.getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers) || !Modifier.isPrivate(modifiers)) {
                continue;
            }
            field.setAccessible(true);
            fieldList.add(field);
        }
        Class superClass = classes.getSuperclass();
        if (superClass != null) {
            eachFieldNoJpa(fieldList, superClass);
        }

    }
}
